<template>
  <el-scrollbar class="p-3 pb-7" @click="onClick">
    <div
      v-html="articleStore.getCurrentArticle?.htmlContent"
      v-right-click="contextMenuList"
      class="editable-div"
      id="edit_container"
      placeholder="为你的翻译开始做笔记吧！"
      contenteditable
      :spellcheck="spellcheck"
      @click.stop
      @mousemove="editableEvents.onMouseMove"
      @mouseout="editableEvents.onMouseOut"
      @mousedown="editableEvents.onMouseDown"
      @mouseup.stop="editableEvents.onSelectedTextMouseUp"
      @compositionend="editableEvents.onCompositionend"
      @input="editableEvents.onTotalContentInput"
    ></div>
  </el-scrollbar>
  <cl-context-menu
    v-if="contextMenuList.length > 0"
    :rightMenuList="contextMenuList"
  ></cl-context-menu>
</template>

<script setup lang="ts">
import type { RightMenuItem } from "@/components/cl-context-menu";
import { useArticleStore } from "@/store/modules/article";
import { editableEvents } from "../../eventHandlers";
import { spellcheck } from "./index";
import { rangeHandler } from "../../range";

const articleStore = useArticleStore();

const contextMenuList = ref<RightMenuItem[]>([]);

function onContextMenu(e: MouseEvent) {
  const target = e.target as HTMLElement;
  const styleList: (keyof CSSStyleDeclaration)[] = [
    "backgroundColor",
    "textDecoration",
    "fontWeight",
  ];
  contextMenuList.value = styleList.reduce((pre, cur, idx) => {
    if (target.style[cur]) {
      pre.push({
        id: idx,
        text: cur as string,
        handler: () => {},
      });
    }
    return pre;
  }, [] as RightMenuItem[]);
  console.log(contextMenuList.value, "contextMenuList.value");

  setHTMLElementStyle(target, {
    backgroundColor: "#b2d7fd",
  });
}

//激活光标
function onClick() {
  const editorDom = getEditorDom()!;
  editorDom?.focus();
  const lastNode = getLastDeepestNode(editorDom);
  if (!lastNode) return;

  //将光标定位到最后
  let offset = 0;
  if (lastNode.nodeType === Node.TEXT_NODE) {
    offset = lastNode.textContent!.length;
  }
  rangeHandler.createAndInsertRange(lastNode, offset);
}
</script>

<style scoped lang="scss">
.editable-div {
  //允许多个空格
  white-space: break-spaces;
  // 激活后
  &:focus-within {
    outline: none;
  }
  &:empty::before {
    content: attr(placeholder);
    color: gray;
  }
}
</style>
